<!-- eslint-disable no-unused-vars -->
<template>
  <div class="employees-container">
    <div class="app-container">
      <table-tool>
        <template #left>
          <div class="total">
            <i class="el-icon-info" />
            <span>共{{ total }}条记录</span>
          </div>
        </template>
        <template #right>
          <el-button type="danger" size="small" @click="exportExcel">普通excel导出</el-button>
          <el-button type="info" size="small">复杂表头excel导出</el-button>
          <el-button type="success" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="primary" size="small" @click="addBtn">新增员工</el-button>
        </template>
      </table-tool>
      <!--表格 -->
      <el-card class="box-card" style="margin-top: 10px;">
        <el-table
          :data="employeesInfo"
          stripe
          border
          style="width: 100%"
        >
          <el-table-column
            type="index"
            width="80"
            label="序号"
            align="center"
          />
          <el-table-column
            prop="username"
            label="姓名"
            width="100"
            sortable
            align="center"
          />
          <el-table-column
            label="头像"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <img v-if="scope.row.staffPhoto.trim()" :src="scope.row.staffPhoto" alt="" class="user-avatar" style="" @click="creatQrCode(scope.row)">
              <img v-else :src="avatar" alt="" class="user-avatar" @click="creatQrCode(scope.row)">
            </template>
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="手机号"
            width="110"
            sortable
            align="center"
          />
          <el-table-column
            prop="workNumber"
            label="工号"
            width="100"
            sortable
            align="center"
          />
          <el-table-column
            label="聘用形式"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.formOfEmployment | capitalize }}
            </template>
          </el-table-column>
          <el-table-column
            prop="departmentName"
            label="部门"
            width="100"
            sortable
            align="center"
          />
          <el-table-column
            label="入职时间"
            width="120"
            sortable
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry | dateFilter }}
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            label="状态"
            width="80"
            align="center"
          >
            <el-switch
              v-model="value2"
              disabled
              align="center"
            />
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">

              <el-button type="text" size="small" @click="jumpDetail(scope.row)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRoleInfo(scope.row)">角色</el-button>
              <!-- checkPermission('POINT-USER-DELETE') 检查用户是否有权限删除，mixins引入的方法 -->
              <el-button v-if="checkPermission('POINT-USER-DELETE')" type="text" size="small" @click="delEmployeeInfo(scope.row)">删除</el-button>

            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 分页 -->
      <el-pagination
        layout=" prev, pager, next ,jumper"
        :total="total"
        :page-size="pagesize"
        :current-page.sync="page"
        @current-change="handleCurrentChange"
      />

      <!-- 新增弹出框 -->
      <el-dialog
        :close-on-click-modal="false"
        title="新增员工"
        :visible.sync="dialogVisible"
        width="50%"
        @close="closeDialog"
      >
        <el-form ref="employeesForm" :model="employeesForm" :rules="rules" label-width="100px" class="demo-employeesForm">
          <el-form-item label="姓名" prop="username">
            <el-input v-model="employeesForm.username" placeholder="请输入员工姓名" style="width: 80%;" />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="employeesForm.mobile" placeholder="请输入员工手机号" style="width: 80%;" />
          </el-form-item>
          <el-form-item label="入职时间" required>
            <el-date-picker v-model="employeesForm.timeOfEntry" type="date" placeholder="请选择入职日期" style="width: 80%;" />
          </el-form-item>
          <el-form-item label="聘用形式" prop="formOfEmployment">
            <el-select v-model="employeesForm.formOfEmployment" placeholder="请选择负责人" style="width: 80%;">
              <el-option label="正式" :value="1" />
              <el-option label="非正式" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="工号" prop="workNumber">
            <el-input v-model="employeesForm.workNumber" placeholder="请输入工号" style="width: 80%" />
          </el-form-item>
          <el-form-item label="部门" prop="departmentName">
            <el-input v-model="employeesForm.departmentName" placeholder="请选择员工部门" style="width: 80%" @focus="getDepartmentInfo" />
            <el-tree v-if="isShow" :data="departmentList" :props="{ label: 'name' }" @node-click="handleNodeClick" />
          </el-form-item>
          <el-form-item label="转正时间">
            <el-date-picker v-model="employeesForm.timeOfEntry" type="date" placeholder="请选择转正日期" style="width: 80%;" />
          </el-form-item>
        </el-form>
        <el-row slot="footer" type="flex" justify="center">
          <!-- 列被分为24 -->
          <el-col :span="6">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleConfirm">确 定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <!-- 角色弹出框 -->
      <el-dialog
        :close-on-click-modal="false"
        title="分配角色"
        :visible.sync="roleDialog"
        width="50%"
      >
        <el-checkbox-group v-model="roleIds">
          <el-checkbox v-for="(item,index) in roleList" :key="index" :label="item.id">{{ item.name }}</el-checkbox>

        </el-checkbox-group>
        <el-row slot="footer" type="flex" justify="center">
          <!-- 列被分为24 -->
          <el-col :span="6">
            <el-button @click="roleDialog = false">取 消</el-button>
            <el-button type="primary" @click="handleRoleConfirm">确 定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <el-dialog
        :close-on-click-modal="false"
        title="二维码"
        :visible.sync="qrCodeDialog"
        width="30%"
      >
        <div id="qrcode" ref="qrcode" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getDepartment } from '@/api/departments' // 组织架构
import { getRoleList } from '@/api/setting'
import { getEmployees, addEmployee, delEmployee, getEmployeeById, assignRoles } from '@/api/employees' // 员工管理
import { tranListToTreeData } from '@/utils/index' // 转换树形结构
import QRCode from 'qrcodejs2' // 二维码插件
import mixin from '@/mixin/index'
export default {
  // 过滤器（是否为正式员工）
  filters: {
    capitalize: function(value) {
      if (Number(value) === 1) {
        return '正式员工'
      } else if (Number(value) === 2) {
        return '非正式员工'
      } else {
        return '未知'
      }
      // eslint-disable-next-line no-unreachable
      return value
    }
  },

  mixins: [mixin], // 注入mixin
  data() {
    return {
      avatar: 'https://lf-cdn-tos.bytescm.com/obj/static/xitu_extension/static/github.46c47564.png', // 默认头像
      qrCodeDialog: false, // 二维码弹出框
      page: 1,
      pagesize: 10,
      total: 0,
      value2: false,
      dialogVisible: false, // 新增弹出框
      roleDialog: false, // 角色分配弹出框
      isShow: false, // tree 是否显示
      departmentList: [], // 组织架构列表
      roleIds: [], // 选择的角色列表
      roleList: [], // 角色列表
      id: '', // 员工id
      employeesInfo: [{
        /**
     * 员工转正日期，格式: 2020-01-01
     */
        correctionTime: '',
        /**
     * 员工部门名字
     */
        departmentName: '',
        /**
     * 员工聘用形式，1正式, 2非正式
     */
        formOfEmployment: null,
        /**
     * 员工id
     */
        id: '',
        /**
     * 员工手机号
     */
        mobile: '',
        /**
     * 员工密码
     */
        password: '',
        /**
     * 员工头像地址，完整地址, 直接用
     */
        staffPhoto: '',
        /**
     * 员工入职日期，格式: 2020-01-01
     */
        timeOfEntry: '',
        /**
     * 员工名字
     */
        username: '',
        /**
     * 员工工号
     */
        workNumber: ''
      }], // 员工信息
      employeesForm: {
        correctionTime: '', // 员工转正日期，
        departmentName: '', // 员工部门名字
        formOfEmployment: null, // 员工聘用形式，1正式, 2非正式
        mobile: '', // 员工手机号
        timeOfEntry: '', // 员工入职日期
        username: '', // 员工名字
        workNumber: ''// 员工工号
      }, // 添加员工表单信息
      rules: {
        username: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' }

        ],
        mobile: [
          { required: true, message: '请输入员工手机号', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }

        ],
        formOfEmployment: [
          { required: true, message: '请选择员工聘用形式', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '请选择员工部门', trigger: 'blur' }
        ],
        workNumber: [
          { required: true, message: '请输入员工工号', trigger: 'blur' }
        ]
      }
    }
  },

  async created() {
    await this.getEmployeesInfo()
    await this.getDepartmentInfo()
    await this.getRoleInfo()
  },

  methods: {
    // 处理分页
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeesInfo()
    },
    // 获取员工列表
    async getEmployeesInfo() {
      const { data } = await getEmployees(this.page, this.pagesize)
      this.employeesInfo = data.rows
      this.total = data.total
      console.log(data.rows)
    },
    // 获取部门列表
    async getDepartmentInfo() {
      this.isShow = true
      const { data } = await getDepartment()
      this.departmentList = tranListToTreeData(data.depts, '')
    },
    // 获取角色列表
    async getRoleInfo() {
      const { data } = await getRoleList()
      console.log(data)
      this.roleList = data.rows
    },
    // 添加员工按钮
    addBtn() {
      this.dialogVisible = true
      this.isShow = false
    },
    // 清空表单
    clearForm() {
      for (const key in this.employeesForm) {
        this.employeesForm[key] = ''
      }
    },
    // 关闭弹窗重置表单
    closeDialog() {
      this.clearForm()
      this.$refs.employeesForm.clearValidate()
      this.isShow = false
    },
    // 点击部门树赋值
    handleNodeClick(data) {
      this.employeesForm.departmentName = data.name
      this.isShow = false
    },
    // 新增员工
    async handleConfirm() {
      this.$refs.employeesForm.validate(async valid => {
        if (valid) {
          const res = await addEmployee(this.employeesForm)
          if (res.success) {
            this.$message({
              type: 'success',
              message: res.message
            })
            this.dialogVisible = false
            this.getEmployeesInfo()
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        }
      })
    },
    // 删除员工
    async delEmployeeInfo(data) {
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployee(data.id)
        if (res.success) {
          this.$message({
            type: 'success',
            message: res.message
          })
          this.getEmployeesInfo()
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 编辑角色
    async editRoleInfo(item) {
      this.id = item.id
      const { data } = await getEmployeeById(this.id)
      if (data.roleIds === null) {
        this.roleIds = []
      } else {
        this.roleIds = data.roleIds
      }
      this.roleDialog = true
    },
    // 角色修改确定
    async handleRoleConfirm() {
      console.log(this.roleIds)
      const res = await assignRoles(this.id, this.roleIds)
      if (res.code === 10000) {
        this.$message({
          type: 'success',
          message: res.message
        })
      } else {
        this.$message({
          type: 'error',
          message: res.message
        })
      }
      this.roleDialog = false
    },
    // 跳转
    jumpDetail(data) {
      console.log(data.id)
      this.$router.push(`/employees/${data.id}`)
    },
    // 导出表格
    exportExcel() {
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象      //import方法执行完毕返回的是一个promise对象，
        // 在then方法中我们可以拿到使用的模块对象
        // console.log(excel)
        const header = {
          '姓名': 'username',
          '手机号': 'mobile',
          '工号': 'workNumber',
          '部门': 'departmentName',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment'
        }
        const data = this.employeesInfo.map(item => {
          return Object.keys(header).map(key => {
            return item[header[key]]
          })
        })
        excel.export_json_to_excel({
          header: Object.keys(header), // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 生成二维码
    creatQrCode(data) {
      this.qrCodeDialog = true
      this.$nextTick(() => {
        this.$refs.qrcode.innerHTML = ''
        // eslint-disable-next-line no-unused-vars
        var qrcode = new QRCode(this.$refs.qrcode, {
          text: data.staffPhoto || this.avatar, // 需要转换为二维码的内容
          width: 150,
          height: 150,
          colorDark: '#000000',
          colorLight: '#ffffff'
        })
      })
    },
    mounted() {
      this.$nextTick(() => {
        this.creatQrCode()
      })
    }

  }
}

</script>

<style lang="scss" scoped>
.employees-container{
  .total{
    width: 125px;
    height: 36px;
    border: 1px solid#91d5ff;
    background:#e6f7ff;
    color:#53a8ff;
    border-radius: 3px;
    text-align: center;
    line-height: 36px;
    span{
      color: #000;
    }
  }
    .user-avatar{
      width: 60px;
      height: 60px;
      border-radius: 30px;
    }
  .el-pagination{
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
#qrcode{
  height: 150px;
  width: 150px;
  margin: 0 auto;
}
}
</style>
